<template>
    <div class="sign-in">
        <div class="countdown-container">
            <h2 class="countdown-title">签到倒计时</h2>
            <div class="countdown-timer" v-if="!isEnded">
                <div class="countdown-section">
                    <span class="countdown-value">{{ minutes }}</span>
                    <span class="countdown-label">分</span>
                </div>
                <div class="countdown-section">
                    <span class="countdown-value">{{ seconds }}</span>
                    <span class="countdown-label">秒</span>
                </div>
                <div class="countdown-section">
                    <span class="countdown-value">{{ milliseconds }}</span>
                    <span class="countdown-label">毫秒</span>
                </div>
            </div>

            <div v-if="teacher_role" class="controls">
                <el-select v-model="selectedDuration" placeholder="请选择倒计时时间" v-if="!isStarted">
                    <el-option label="5分钟" value="300000"></el-option>
                    <el-option label="10分钟" value="600000"></el-option>
                    <el-option label="15分钟" value="900000"></el-option>
                    <el-option label="30分钟" value="1800000"></el-option>
                </el-select>
                <el-select v-model="work_value" placeholder="请选择专业" v-if="!isStarted">
                    <el-option v-for="option in work_options" :key="option.value" :label="option.label"
                        :value="option.value"></el-option>
                </el-select>
                <el-button class="buttons" v-if="!isStarted" @click="startCountdown">发布签到</el-button>
                <el-button class="buttons" v-if="isStarted" @click="showCancelDialog">取消签到</el-button>
            </div>
        </div>

        <el-card class="box-card">
            <div slot="header" class="clearfix">
                <span>签到情况</span>
            </div>
            <el-table :data="signList" style="width: 100%" height="300" :row-style="getRowStyle">
                <el-table-column fixed prop="signInId" label="记录ID" width="180"></el-table-column>
                <el-table-column fixed prop="userId" label="学号" width="180"></el-table-column>
                <el-table-column fixed prop="username" label="姓名" width="180"></el-table-column>
                <el-table-column fixed prop="status" label="签到状态" width="200"></el-table-column>
                <el-table-column fixed prop="signInTime" label="签到时间" width="200"></el-table-column>
            </el-table>
        </el-card>

        <!-- 取消签到的对话框 -->
        <el-dialog title="确认取消" :visible.sync="cancelDialogVisible" width="30%" :before-close="handleClose">
            <span>确定要取消签到吗？</span>
            <span slot="footer" class="dialog-footer">
                <el-button @click="cancelDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="confirmCancel">确定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
import SockJS from "sockjs-client";
import Stomp from "webstomp-client";
import { cancleSignIns, pubSignIn } from '@/utils/urlManager';
import "@/utils/InterceptorUtils";
import axios from 'axios';

export default {
    name: "SignIn",
    data() {
        return {
            totalMilliseconds: 0, // 总倒计时时间（毫秒）
            intervalId: null,
            isStarted: false,
            isEnded: false,
            minutes: 0,
            seconds: 0,
            milliseconds: 0,
            selectedDuration: '300000', // 默认选中的倒计时时间
            deadline: null, // 截止时间
            student_role: false,
            teacher_role: false,
            work_options: [
                { value: 'wenhua_001', label: '软件工程' },
                { value: 'wenhua_002', label: '计算机程序设计' },
                { value: 'wenhua_003', label: '数据结构与算法' },
                { value: 'wenhua_004', label: '操作系统' },
                { value: 'wenhua_005', label: 'MySQL数据库' },
                { value: 'wenhua_006', label: 'HTML基础' },
                { value: 'wenhua_007', label: '编译原理' },
                { value: 'wenhua_008', label: 'Java基础' },
                { value: 'wenhua_009', label: '软件测试' },
                { value: 'wenhua_010', label: 'C语言基础' }
            ],
            work_value: '', // 选中的专业

            signInData: {
                signInId: '',
                userId: "",
                username: "",
                asignTime: "",
                value: ""
            },
            signList: [],
            value: '',
            cancelDialogVisible: false, // 控制取消签到对话框的显示
        };
    },
    methods: {
        showWorks() {
            this.$message.success("专业显示成功~")
        },
        teacher_connect() {
            const socket = new SockJS("http://localhost:8888/ws");
            this.stompClient = Stomp.over(socket);
            this.stompClient.connect({}, (frame) => {
                console.log("Connected: " + frame);
                this.stompClient.subscribe("/topic/hasSign", (message) => {
                    if (message.body) {
                        const userId = message.body; // 假设 message.body 是 userId 的值
                        this.handleWebSocketMessage(userId); // 调用处理方法
                    }
                });
            }, (error) => {
                console.error("STOMP error", error);
            });
        },
        handleWebSocketMessage(userId) {
            // 找到对应的签到记录
            const signInRecord = this.signList.find(record => record.userId === userId);
            if (signInRecord) {
                signInRecord.status = "present"; // 更新状态为 present
                this.$message.success(`用户 ${userId} 已签到`);
            } else {
                this.$message.warning(`未找到用户 ${userId} 的签到记录`);
            }
        },
        getRowStyle({ row }) {
            if (row.status === "present") {
                return { backgroundColor: "green", color: "white" }; // 绿色背景，白色文字
            }
            return {}; // 默认样式
        },
        updateCountdown() {
            const now = new Date().getTime();
            const timeLeft = this.deadline - now;

            if (timeLeft <= 0) {
                clearInterval(this.intervalId);
                this.isEnded = true;
                this.isStarted = false; // 倒计时结束后，将 isStarted 设置为 false
                this.showEndMessage(); // 显示结束提示
                this.saveState(); // 保存状态
                return;
            }

            this.minutes = Math.floor(timeLeft / (60 * 1000));
            this.seconds = Math.floor((timeLeft % (60 * 1000)) / 1000);
            this.milliseconds = Math.floor((timeLeft % 1000) / 10); // 显示10毫秒为单位
            this.saveState(); // 保存状态
        },
        calculateEndTime() {
            // 获取当前时间
            const now = new Date();
            // 将选择的时间（毫秒）加到当前时间
            const endTime = new Date(now.getTime() + parseInt(this.selectedDuration, 10));
            // 格式化为 ISO_DATE_TIME 格式
            const endTimeISOString = endTime;
            // 原始时间字符串
            const originalTime = endTimeISOString;

            // 使用 Date 对象解析时间字符串
            const date = new Date(originalTime);

            // 获取年、月、日、时、分、秒
            const year = date.getFullYear(); // 年
            const month = String(date.getMonth() + 1).padStart(2, '0'); // 月（getMonth() 返回的是0-11，需要加1）
            const day = String(date.getDate()).padStart(2, '0'); // 日
            const hours = String(date.getHours()).padStart(2, '0'); // 时
            const minutes = String(date.getMinutes()).padStart(2, '0'); // 分
            const seconds = String(date.getSeconds()).padStart(2, '0'); // 秒

            // 拼接成 YYYY-MM-DD HH:MM:SS 格式
            const formattedTime = `${year}-${month}-${day}T${hours}:${minutes}:${seconds}`;
            console.log(formattedTime);

            return formattedTime;
        },
        startCountdown() {
            if (!this.work_value) {
                this.$alert('请选择专业', '提示', {
                    confirmButtonText: '确定',
                    type: 'warning'
                });
                return;
            }
            axios.put(pubSignIn, {
                "subjectId": this.work_value,
                "endline": this.calculateEndTime()
            })
                .then((response) => {
                    if (response.data.data != null) {
                        console.log(response.data);
                        
                        this.$message.success("签到发布成功！！");
                        this.signList = [];
                        this.signList = response.data.data.signIns;
                        localStorage.setItem("signList", JSON.stringify(response.data.data.signIns));
                        const now = new Date().getTime();
                        this.deadline = now + parseInt(this.selectedDuration, 10);
                        this.isStarted = true;
                        this.isEnded = false;
                        this.intervalId = setInterval(this.updateCountdown, 10); // 每10毫秒更新一次
                        this.updateCountdown(); // 立即更新一次
                        this.saveState(); // 保存状态
                    } else {
                        this.$message.warning(response.data.msg);
                    }
                })
                .catch((err) => {
                    this.$message.error(err)
                    console.log(err);
                })
        },
        showCancelDialog() {
            this.cancelDialogVisible = true;
        },
        confirmCancel() {
            axios.put(cancleSignIns,null, {
                params: {
                    "subjectId": this.work_value
                }
            })
                .then((response) => {
                    if (response.data.data > 0) {
                        clearInterval(this.intervalId); // 停止倒计时
                        this.isStarted = false; // 设置倒计时为未开始状态
                        this.isEnded = true; // 设置倒计时为已结束状态
                        this.signList = []; // 清空签到列表
                        this.saveState(); // 保存状态
                        this.$message.info('签到已取消'); // 显示提示
                        this.cancelDialogVisible = false; // 关闭对话框
                    }
                })
                .catch((err) => {
                    console.error(err);
                    this.$message.error(err);
                })
        },
        handleClose(done) {
            this.$confirm('确认关闭？')
                .then(_ => {
                    done();
                })
                .catch(_ => { });
        },
        showEndMessage() {
            this.$message.success("签到结束啦~~")
        },
        saveState() {
            // 保存倒计时状态到localStorage
            localStorage.setItem('deadline', this.deadline);
            localStorage.setItem('isEnded', this.isEnded);
            localStorage.setItem('isStarted', this.isStarted);
            localStorage.setItem('work_value', this.work_value); // 保存选中的专业
        },
        loadState() {
            // 从localStorage加载倒计时状态
            const savedDeadline = localStorage.getItem('deadline');
            const savedIsEnded = localStorage.getItem('isEnded');
            const savedIsStarted = localStorage.getItem('isStarted');
            const savedWorkValue = localStorage.getItem('work_value');

            if (savedDeadline) {
                this.deadline = parseInt(savedDeadline, 10);
                this.isEnded = savedIsEnded === 'true';
                this.isStarted = savedIsStarted === 'true';
                this.work_value = savedWorkValue; // 加载选中的专业
                if (!this.isEnded && this.isStarted) {
                    this.updateCountdown();
                    this.intervalId = setInterval(this.updateCountdown, 10); // 恢复倒计时
                }
            }
        },
        addStatue() {
            this.signInData.value = this.value
        },
        handleSubmit() {
            if (this.signList.length > 0) {
                const isSigned = this.signList.some(item => item.userId === this.signInData.userId);
                if (isSigned) {
                    this.$message.warning("这个学生签到过咯~~");
                    return false;
                }
            }

            if (!this.signInData.username || !this.signInData.asignTime || !this.signInData.userId || !this.signInData.value) {
                this.$message.error("请填写完整信息！");
                return;
            }

            this.signList.push({
                username: this.signInData.username,
                asignTime: this.signInData.asignTime,
                userId: this.signInData.userId,
                value: this.signInData.value,
            });
            this.signInData.username = "";
            this.signInData.asignTime = "";
            this.signInData.userId = "";
            this.signInData.value = "";
            this.$message.success("签到成功！");
        },
        getSignList() {
            this.signList = null;
            this.signList = localStorage.getItem("signList") == null ? null : JSON.parse(localStorage.getItem("signList"));
        },
    },
    mounted() {
        this.loadState(); // 加载保存的状态
        if (localStorage.getItem("role") == "1") {
            this.student_role = true;
        } else if (localStorage.getItem("role") == "2") {
            this.teacher_role = true;
        }

        this.getSignList();
        this.teacher_connect();
    },
    beforeDestroy() {
        if (this.intervalId) {
            clearInterval(this.intervalId);
        }
        this.saveState(); // 保存状态
    },
};
</script>
<style scoped>
.sign-in {
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 100%;
}

.box-card {
    width: 80%;
    margin: 20px 0;
}

.countdown-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background-color: #f0f0f0;
    border-radius: 10px;
    padding: 20px;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    max-width: 100%;
    margin: 0 auto;
}

.countdown-title {
    font-size: 24px;
    font-weight: bold;
    color: #333;
    margin-bottom: 20px;
}

.countdown-timer {
    display: flex;
    justify-content: center;
    align-items: center;
}

.countdown-section {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin: 0 10px;
}

.countdown-value {
    font-size: 70px;
    font-weight: bold;
    color: #4caf50;
    margin-bottom: 5px;
    transition: color 0.3s ease;
}

.countdown-label {
    font-size: 24px;
    color: #666;
    width: 20vw;
}

.controls {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-top: 20px;
}

.start-button {
    background-color: #4caf50;
    color: white;
    border: none;
    border-radius: 5px;
    padding: 10px 20px;
    font-size: 16px;
    cursor: pointer;
    margin-top: 10px;
}

.start-button:hover {
    background-color: #45a049;
}
</style>